package com.wk.net.heartbeat.handler;

import java.util.concurrent.BlockingQueue;

/**
 * 任务类：处理收到的心跳包<br>
 * 由于是单独的线程，故允许执行耗时操作
 * 
 * @author Bai Yu
 *
 */
class HandleHeartbeat<HeartbeatType> implements Runnable {
	/**
	 * 处理收到的心跳包
	 * 
	 * @param heartbeats
	 *            容器，存储收到的心跳包<br>
	 *            只有容器中仍有元素，就一个一个地取出并处理
	 * @param listener
	 *            心跳包的处理策略<br>
	 *            允许执行耗时操作
	 * @param observer
	 *            收集参数：对新发现的心跳源新增监视
	 */
	public HandleHeartbeat(BlockingQueue<ParsedHeartbeatMessage<HeartbeatType>> heartbeats,
			HeartbeatListener<HeartbeatType> listener, HeartbeatObserver observer) {
		this.heartbeats = heartbeats;
		this.listener = listener;
		this.observer = observer;
	}

	@Override
	public void run() {
		while (true) {
			try {
				ParsedHeartbeatMessage<HeartbeatType> heartbeat = heartbeats.take();
				listener.onHeartbeat(heartbeat);
				listener.alterObservation(heartbeat, observer);
			} catch (InterruptedException e) {
				break;
			}
		}
	}

	private BlockingQueue<ParsedHeartbeatMessage<HeartbeatType>> heartbeats;
	private HeartbeatListener<HeartbeatType> listener;
	private HeartbeatObserver observer;
}
